﻿using Core;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public partial class NineGrid
{
    public class Node
    {
        public int Cnt = 3;
        public GameObject Go { get; private set; }
        private GridLayoutGroup m_layout;
        private List<GameObject> m_childs = new List<GameObject>();

        public void Awake(GameObject go)
        {
            Go = go;
            m_layout = go.GetComponent<GridLayoutGroup>();

            m_childs.Clear();
            int child_cnt = Go.transform.childCount;

            if (child_cnt == 0)
            {
                log.err($"Error! GridResizer至少需要一个子节点");
                return;
            }

            for (int i = 0; i < child_cnt; i++)
            {
                m_childs.Add(Go.transform.GetChild(i).gameObject);
            }
        }

        public void InitGrid(int ss, Vector2 size)
        {
            Cnt = ss;
            var total = ss * ss;

            m_layout.childAlignment = TextAnchor.MiddleCenter;
            m_layout.constraint = GridLayoutGroup.Constraint.FixedColumnCount;
            m_layout.constraintCount = ss;

            var cnt = m_childs.Count;
            if (total > cnt)
            {
                var delta = total - cnt;
                var template = m_childs[0];
                for (int i = 0; i < delta; i++)
                {
                    var go = GameObject.Instantiate(template);
                    go.transform.parent = Go.transform;
                    go.name = (i + cnt + 1).ToString();
                    m_childs.Add(go);
                }
            }
            else if (total < cnt)
            {
                for (int i = cnt - 1; i >= total; i--)
                {
                    var go = m_childs[i];
                    m_childs.RemoveAt(i);
                    GameObject.DestroyImmediate(go);
                }
            }

            var padding_h = m_layout.padding.left + m_layout.padding.right;
            var padding_v = m_layout.padding.top + m_layout.padding.bottom;

            float A = 8;
            float B = 2;

            var x = (size.x - padding_h) / (Cnt * A + (Cnt - 1) * B);
            var y = (size.y - padding_v) / (Cnt * A + (Cnt - 1) * B);

            var item_width = A * x;
            var item_height = A * y;

            var cell_size = Mathf.Min(item_width, item_height);
            m_layout.cellSize = new Vector2(cell_size, cell_size);

        }

    }
}
